function StageAssistant() {
	/* this is the creator function for your stage assistant object */
}

// Global for the unique ID
myUID = "";
companyID = "";
companyName = "";
companyShortcut = "";
companyNumber = "";
companyDial = "";
companyURL = "";
altContact = "";
altShortcut = "";
altType = "";
entireList = [];
optionsList = [];
refreshData = true;
internetConnection = false;
ONE_DAY = 1000 * 60 * 60 * 24;


StageAssistant.prototype.setup = function() {
	/* this function is for setup tasks that have to happen when the stage is first created */
	
	this.controller.pushScene("companyIndex");
	

	//Test for internet connection
	/*
	var connectionAttr = {
		     method: 'getstatus',
		     parameters: {},
		     onSuccess: function(response){
		    	internetConnection = response.isInternetConnectionAvailable;
		     },
		     onFailure: function(response){}
		 }

	Mojo.Log.info("-------INTERNET CONNECTION:  ", internetConnection);
	new Mojo.Service.Request('palm://com.palm.connectionmanager', connectionAttr);
	*/
	
	this.dataPull = new Mojo.Model.Cookie("dataPull");
	var current_date = new Date();
	this.day = current_date.getTime();

	this.oldDate = this.dataPull.get();
	if (isNaN(this.oldDate * 1)){
		if (this.day != '') {
			 this.dataPull.put(this.day);
			}
		refreshData = true;
		this.oldDate = this.dataPull.get();
	}
	else if (((this.day - this.oldDate)/ONE_DAY)> 7 )
	{
		refreshData = true;
		this.dataPull.remove();
	}
	else
	{
		refreshData = false;
	}

	
	this.myDb = new Database("gethumanDB", "1", true, "GetHuman Company Data List", 600000);
	
	if (refreshData){
		var sql = "DROP TABLE IF EXISTS 'companyTable'";  // Drops old table from database for updating
		this.myDb.runQuery(sql, this.mySuccessCallback.bind(this), this.myFailCallback.bind(this));
		
		sql = "CREATE TABLE IF NOT EXISTS 'companyTable' (id INTEGER PRIMARY KEY, title TEXT, cid REAL, shortcut TEXT, dialNumber TEXT, displayNumber TEXT, companyURL TEXT)";  // Creates new empty table
		this.myDb.runQuery(sql, this.mySuccessCallback.bind(this), this.myFailCallback.bind(this));
					
			
		// Get unique device ID
		var deviceIdAttributes = {method: 'getSysProperty', 
				parameters: {'key': 'com.palm.properties.nduid'}, 
				onSuccess: this.deviceIDServiceRequestHandler.bind(this)
				}

		new Mojo.Service.Request('palm://com.palm.preferences/systemProperties', deviceIdAttributes);

		//AJAX data request
		var url = REPLACE_WITH_API_CALL

		var request = new Ajax.Request(url, {
			method: 'get',
			onSuccess: this.processData.bind(this),
			onFailure: this.ajaxFailure.bind(this),
			on0: this.dataFailure.bind(this)
			});
	}
	else{
		var sql = "SELECT * FROM 'companyTable'";
		this.myDb.runQuery(sql, this.dataHandler.bind(this), this.myFailCallback.bind(this));
	}
	
	
};


StageAssistant.prototype.mySuccessCallback = function(results) {

	//Mojo.Log.info("-------SUCCESS CALLBACK");

};

StageAssistant.prototype.myFailCallback = function(error) {
	
	Mojo.Log.error("-------FAIL CALLBACK");

};

StageAssistant.prototype.deviceIDServiceRequestHandler = function(resp){
	//Gets the uid from palm and stores it globally
	myUID = resp['com.palm.properties.nduid'];
	
};

StageAssistant.prototype.processData = function(transport) {
	
	this.dataList = [];
	this.companyData = [];
	this.dataList = transport.responseText.split("\n");

	for ( var i=0, len=this.dataList.length; i<len; ++i ){
		this.companyData = this.dataList[i].split("\t");
		if (this.companyData[0] != '' && !isNaN(this.companyData[1] * 1)){
		entireList.push({title: this.companyData[0],
			cid: this.companyData[1],
			shortcut: this.companyData[2],
			dialNumber: this.companyData[3],
			displayNumber: this.companyData[4],
			companyURL: this.companyData[11]
			});
		}
	}    
		
	var db = openDatabase("gethumanDB", "1");
	db.transaction( function (transaction) {
		  for(var i=0; i < entireList.length; i++) {
		    var sql = "INSERT INTO 'companyTable' (title, cid, shortcut, dialNumber, displayNumber, companyURL) VALUES (?, ?, ?, ?, ?, ?)";
		    transaction.executeSql(sql,  [entireList[i].title, entireList[i].cid, entireList[i].shortcut, entireList[i].dialNumber, entireList[i].displayNumber, entireList[i].companyURL], 
		                           function(transaction, results) {    // success handler
		                           },
		                           function(transaction, error) {      // error handler
		                             Mojo.Log.error("Could not insert record: " + error.message);
		                           }
		    );
		  }
		});
		
	var sql = "SELECT * FROM 'companyTable'";
	this.myDb.runQuery(sql, this.dataHandler.bind(this), this.myFailCallback.bind(this));
	 
};


StageAssistant.prototype.dataHandler = function(results) {
	
	if(!refreshData){
		for ( var i=0, len=results.rows.length; i<len; ++i ){
			entireList.push({title: results.rows.item(i).title,
				cid: results.rows.item(i).cid,
				shortcut: results.rows.item(i).shortcut,
				dialNumber: results.rows.item(i).dialNumber,
				displayNumber: results.rows.item(i).displayNumber,
				companyURL: results.rows.item(i).companyURL
				});
		} 
	}
	
	entireList.sort(function(a, b){
		 var titleA=a.title.toLowerCase(), titleB=b.title.toLowerCase()
		 if (!isNaN(titleA[0] * 1) && isNaN(titleB[0] * 1))//Sort numbers to the end of the list.
			 return 1
		 if (!isNaN(titleB[0] * 1) && isNaN(titleA[0] * 1))
			 return -1
		 if (titleA < titleB) //sort string ascending
			 return -1 
		 if (titleA > titleB)
			 return 1
		 return 0 //default return value (no sorting)
		})
	

	filterlist.mojo.noticeUpdatedItems(0, entireList);
	filterlist.mojo.setLength(entireList.length);
	filterlist.mojo.setCount(entireList.length);
	this.controller.get('overlay-scrim').hide();
	
};	

StageAssistant.prototype.dataFailure = function(transport) {

	this.controller.get('overlay-scrim').hide();
	Mojo.Log.info("-----------No data was returned from Ajax Request");
	Mojo.Controller.errorDialog("Error loading data from the GetHuman database");
};

StageAssistant.prototype.ajaxFailure = function(transport) {

	this.controller.get('overlay-scrim').hide();
	var status = transport.status;
	Mojo.Log.info("........","Invalid URL (Status ", status, " returned).");
	Mojo.Controller.errorDialog("Error loading data from the GetHuman database");
};